import {reactive} from 'vue'

const MIN_DISTANCE = 10

function getDirection(x:number, y:number) {
    if (x > y && x > MIN_DISTANCE) {
        return 'horizontal'
    }
    if (y > x && y > MIN_DISTANCE) {
        return 'vertical'
    }
    return ''
}
export const useTouch = () => {
	const touchCtx = reactive({
		direction:'',
		deltaX:0,
		deltaY:0,
		offsetX:0,
		offsetY:0,
		startX:0,
		startY:0
	})
	const getTouchPoint = (e:any) => {
	    if (!e) {
	        return {
	            x: 0,
	            y: 0
	        }
	    } if (e.touches && e.touches[0]) {
	        return {
	            x: e.touches[0].pageX,
	            y: e.touches[0].pageY
	        }
	    } if (e.changedTouches && e.changedTouches[0]) {
	        return {
	            x: e.changedTouches[0].pageX,
	            y: e.changedTouches[0].pageY
	        }
	    }
	    return {
	        x: e.clientX || 0,
	        y: e.clientY || 0
	    }
	}
	const resetTouchStatus = () => {
	    touchCtx.direction = ''
	    touchCtx.deltaX = 0
	    touchCtx.deltaY = 0
	    touchCtx.offsetX = 0
	    touchCtx.offsetY = 0
	}
	const touchStart = (event:any) => {
	    resetTouchStatus()
	    const touch = getTouchPoint(event)
	    touchCtx.startX = touch.x
	    touchCtx.startY = touch.y
	}
	const touchMove = (event:any) => {
	    const touch = getTouchPoint(event)
	    touchCtx.deltaX = touch.x - touchCtx.startX
	    touchCtx.deltaY = touch.y - touchCtx.startY
	    touchCtx.offsetX = Math.abs(touchCtx.deltaX)
	    touchCtx.offsetY = Math.abs(touchCtx.deltaY)
	    touchCtx.direction =				touchCtx.direction || getDirection(touchCtx.offsetX, touchCtx.offsetY)
	}
	
	return {
		touchCtx,
		getTouchPoint,
		resetTouchStatus,
		touchStart,
		touchMove
	}
}